package br.unb.graphics;

import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class LoadingBar extends /*JFrame*/ JPanel implements Runnable {

    JProgressBar pbar;
    static final int MY_MINIMUM = 0;
    static final int MY_MAXIMUM = 100;
    static int currentValue = 0;
    private boolean isRunning = false;
    Thread timer;

    public LoadingBar() {
        super();
        pbar = new JProgressBar();
        pbar.setMinimum(MY_MINIMUM);
        pbar.setMaximum(MY_MAXIMUM);
        this.add(pbar);
        this.setVisible(false);
        timer = new Thread(new Runnable() {

            public void run() {
                while (isRunning) {
                    try {
                        currentValue++;
                        if (currentValue >= 100) {
                            currentValue = 0;
                        }
                        if (pbar.isVisible()) {
                            pbar.setValue(currentValue);
                        }
                        Thread.sleep(50);
                    } catch (InterruptedException ie) {
                        Thread.yield();
                    }
                }
            }
        }, "LoadingBar-Timer");//Thread name
        timer.setPriority(Thread.NORM_PRIORITY - 1);
    }

    public void stop() {
        isRunning = false;
        this.setVisible(false);
    }

    @Override
    public void run() {
        isRunning = true;
        timer.start();
        this.setVisible(true);
    }
}
